<?php


namespace app\admin\controller\cou;

use app\admin\controller\anx\Adv;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="优惠券")
 */
class Coupon extends AdminController
{

    use \app\admin\traits\Curd;
    protected $sort = [
        'id'   => 'desc',
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new \app\admin\model\Coupon();
        
    }
    
    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }
 
    /**
    * @NodeAnotation(title="添加")
    */
    public function add()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if(empty($post['title'])){
                $this->error('名称不能为空');
            }
            if($post['less_amount'] > $post['full_amount']){
                $this->error('减金额不能大于满金额');
            }
            $data = [
                'title'=>$post['title'],
                'full_amount'=>$post['full_amount'],
                'less_amount'=>$post['less_amount'],
                'endtime'=>$post['endtime'],
                'add_time'=>date('Y-m-d H:i:s',time())
            ];
            try {
                $save = $this->model->save($data);
            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }

     /**
    * @NodeAnotation(title="编辑")
    */
    public function edit()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if(empty($post['title'])){
                $this->error('名称不能为空');
            }
            if($post['less_amount'] > $post['full_amount']){
                $this->error('减金额不能大于满金额');
            }
            $data = [
                'full_amount'=>$post['full_amount'],
                'less_amount'=>$post['less_amount'],
                'title'=>$post['title'],
                'endtime'=>$post['endtime'],
            ];
            try { 
               $this->model->where('id',$post['id'])->update($data);
            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $this->success('保存成功');
        }else{
            $post = $this->request->param(); 
            $row = $this->model->where('id',$post['id'])->find();
            if($row['release_or_not'] == 2){
                return '已发放不可编辑';
            }
            $this->assign('row', $row);
        }
        return $this->fetch();
    }

     /**
     * @NodeAnotation(title="删除")
     */
    public function delete($id)
    {
        $row = $this->model->whereIn('id', $id)->select();
        $row->isEmpty() && $this->error('数据不存在');
        $coupon_user = Db::name("coupon_user")->where("coupon_id",$id)->where("status",1)->find();
        if(!empty($coupon_user)){
            $this->error('优惠券已发放未使用，不能删除'); 
        }
        try {
            $save = $row->delete();
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    //发放优惠券
    public function grant(){
        $post = $this->request->param();
        if(empty($post['id'])){
            $this->error('优惠券不存在');
        }
        // $arr = $this->model->where('id',$post['id'])->field('title,money,endtime')->find()->toArray();
        // $arr['tishi'] = "可前往个人中心-优惠券界面查看"; 
        $user = Db::name('user')->field('id as uid')->select()->toArray();
        foreach($user as $k=>$v){
            $user[$k]['coupon_id'] = $post['id'];
            $user[$k]['add_time'] = date('Y-m-d H:i:s',time());
        }
        Db::name('coupon_user')->insertAll($user);
        // $user_qwe = Db::name('user')->order('id asc')->field('id,wx_openid')->select()->toArray();
        // foreach($user_qwe as $k=>$v){
        //     $openid = $v['wx_openid'];
        //     $adv->real_authentication($openid,$arr,2);
        // }
        $this->model->where('id',$post['id'])->update(['release_or_not'=>2]);
        $this->success('发放成功');
    }
 
 
}